//
//  XYPopMenu.swift
//  WeiboSourceCode
//
//  Created by 周星宇 on 15/12/27.
//  Copyright © 2015年 cn.weibo. All rights reserved.
//

import UIKit

class XYPopMenu: UIView {

    
    // MARK: 供外界添加的View
    private var contentView:UIView?
    
    lazy private var coverBtn: UIButton = {() -> UIButton in
        
        let btn = UIButton()
        
        btn.backgroundColor = UIColor.clearColor()
        
        btn.addTarget(self, action: "didClickCover:", forControlEvents:.TouchUpInside)
        
        return btn
    }()
    // 带尖尖的容器
    lazy private var container: UIImageView = {() -> UIImageView in
        
        let containerView = UIImageView()
        let image = UIImage(named: "popover_background")
        
        let halfWidth = (image?.size.width)! * 0.5
        let halfHeight = (image?.size.height)! * 0.5
        image?.resizableImageWithCapInsets(UIEdgeInsetsMake(halfHeight, halfWidth, halfHeight, halfWidth), resizingMode: .Stretch)
        containerView.image = image
        containerView.userInteractionEnabled = true
        return containerView
    }()
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        addSubview(coverBtn)
        addSubview(container)
        
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        coverBtn.frame = self.bounds
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    @objc private func didClickCover(sender:UIButton) {
        
        dismiss()
        
    }
    private func dismiss() {
        
        removeFromSuperview()
    }
    // MARK: 外部方法
    func showInRect(rect:CGRect) {
        
        container.frame = rect
        
        UIApplication.sharedApplication().keyWindow!.addSubview(self)
        
        if contentView != nil{
            container.addSubview(contentView!)
            // 设置内容的frame
            let toTop:CGFloat = 16
            let toBottom:CGFloat = 8
            let toRight:CGFloat = 5
            let toLeft:CGFloat = 5
            contentView?.frame.origin.y = toTop
            contentView?.frame.origin.x = toLeft
            contentView?.frame.size.width = container.frame.size.width - toLeft - toRight
            container.frame.size.height = container.frame.size.height - toTop - toBottom
        }
    }
    convenience init (content:UIView){
        
        self.init()
        
        contentView = content
    
    }
    

}
